import { DeleteOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { useCallback, useEffect, useMemo, useState } from 'react';

import orgService from '@/api/services/orgService';
import { Search, Tree } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import { useRequest2 } from '@/hooks/use-request';
import { useOrchestrationStore } from '@/store/orchestrationStore';

interface Props {
  appId: string;
  onSelect: (selectedDatasets: SelectedDataset[]) => void;
  defaultValue: SelectedDataset[];
}

export interface SelectedDataset {
  key: string;
  title: string;
  type: string;
}

// 提取类型定义
type DatasetState = {
  datasets: SelectedDataset[];
  function: SelectedDataset[];
};

type TabItem = {
  label: string;
  value: string;
};

const SelectDataset = ({ appId, onSelect, defaultValue }: Props) => {
  const { isDisableDataset, isEnableFunctionCalling } = useOrchestrationStore();

  // 按类型分别存储选中的数据集
  const [selectedDatasets, setSelectedDatasets] = useState<DatasetState>({
    datasets: defaultValue.filter((item) => item.type === 'dataset' || item.type === 'folder'),
    function: defaultValue.filter((item) => item.type === 'function'),
  });
  const [searchValue, setSearchValue] = useState('');
  const [activeTab, setActiveTab] = useState('datasets');

  // 提取标签页配置逻辑
  const tabs = useMemo((): TabItem[] => {
    const tabItems: TabItem[] = [];

    if (!isDisableDataset) {
      tabItems.push({
        label: '知识库文件',
        value: 'datasets',
      });
    }

    if (isEnableFunctionCalling) {
      tabItems.push({
        label: '数据接口',
        value: 'function',
      });
    }

    return tabItems;
  }, [isDisableDataset, isEnableFunctionCalling]);

  const getDatasetTree = useCallback(async () => {
    if (!appId) {
      return [];
    }
    const res = await orgService.getDatasetTree({ appId });
    console.log(res);
    return res;
  }, [appId]);

  const { data, loading } = useRequest2(getDatasetTree, {
    manual: false,
    refreshDeps: [appId],
  });

  // 递归转换树形数据的函数
  const transformTreeData = useCallback((items: any[]): any[] => {
    if (!Array.isArray(items)) {
      return [];
    }

    return items.map((item: any) => ({
      title: item.name,
      key: item._id || item.id,
      type: item.type,
      children:
        item.children && Array.isArray(item.children) && item.children.length > 0
          ? transformTreeData(item.children)
          : undefined,
    }));
  }, []);

  // 递归搜索树形数据的函数
  const searchTreeData = useCallback((items: any[], searchValue: string): any[] => {
    if (!Array.isArray(items)) {
      return [];
    }

    return items
      .map((item: any) => {
        const isCurrentMatch = item.title.toLowerCase().includes(searchValue.toLowerCase());
        let matchedChildren: any[] = [];

        if (item.children && Array.isArray(item.children)) {
          matchedChildren = searchTreeData(item.children, searchValue);
        }

        if (isCurrentMatch || matchedChildren.length > 0) {
          return {
            ...item,
            children: matchedChildren.length > 0 ? matchedChildren : undefined,
          };
        }

        return null;
      })
      .filter(Boolean);
  }, []);

  // 提取树形数据处理逻辑
  const processTreeData = useCallback(
    (rawData: any, searchValue: string) => {
      if (!rawData || !Array.isArray(rawData?.list)) {
        return {
          datasets: [],
          function: [],
        };
      }

      const transformedData = transformTreeData(rawData.list);

      if (!searchValue.trim()) {
        return {
          datasets: transformedData.filter(
            (item) => item.type === 'folder' || item.type === 'dataset',
          ),
          function: transformedData.filter((item) => item.type === 'function'),
        };
      }

      const result = searchTreeData(transformedData, searchValue);

      return {
        datasets: result.filter((item) => item.type === 'folder' || item.type === 'dataset'),
        function: result.filter((item) => item.type === 'function'),
      };
    },
    [transformTreeData, searchTreeData],
  );

  const treeData = useMemo(() => {
    return processTreeData(data, searchValue);
  }, [data, searchValue, processTreeData]);

  // 处理树节点选中
  const handleTreeCheck = useCallback(
    (checkedKeys: any, info: any) => {
      const checkedNodes = info.checkedNodes || [];
      const newSelectedDatasets = checkedNodes.map((node: any) => ({
        key: node.key,
        title: node.title,
        type: node.type,
      }));

      setSelectedDatasets((prev) => ({
        ...prev,
        [activeTab]: newSelectedDatasets,
      }));
    },
    [activeTab],
  );

  // 获取当前标签页的选中项，使用 useMemo 避免每次渲染都重新计算
  const currentSelectedDatasets = useMemo(() => {
    return selectedDatasets[activeTab as keyof typeof selectedDatasets] || [];
  }, [selectedDatasets, activeTab]);

  // 获取所有选中项的总数，使用 useMemo 优化
  const totalSelectedCount = useMemo(() => {
    return selectedDatasets.datasets.length + selectedDatasets.function.length;
  }, [selectedDatasets.datasets, selectedDatasets.function]);

  useEffect(() => {
    const datasets = [...selectedDatasets.datasets, ...selectedDatasets.function];
    onSelect(datasets);
  }, [currentSelectedDatasets, onSelect, selectedDatasets.datasets, selectedDatasets.function]);

  // 提取删除数据集逻辑
  const handleDeleteDataset = useCallback((datasetKey: string, type: 'datasets' | 'function') => {
    setSelectedDatasets((prev) => ({
      ...prev,
      [type]: prev[type].filter((item) => item.key !== datasetKey),
    }));
  }, []);

  // 提取渲染已选数据集项的逻辑
  const renderSelectedDatasetItem = (dataset: SelectedDataset, type: 'datasets' | 'function') => (
    <div
      key={dataset.key}
      className="mb-2 flex items-center justify-between gap-2 rounded border border-line-1 bg-fill-1 p-2"
    >
      {dataset.type === 'folder' ? (
        <SvgIcon icon="ri--folder-2-fill" size={18} />
      ) : (
        <SvgIcon icon="mdi--folder-zip" size={18} />
      )}
      <span className="flex-1 truncate text-sm text-gray-700">{dataset.title}</span>
      <Button
        type="text"
        size="small"
        danger
        icon={<DeleteOutlined />}
        onClick={() => handleDeleteDataset(dataset.key, type)}
        className="text-red-500 hover:text-red-700 hover:bg-red-50"
      />
    </div>
  );

  // 提取渲染已选数据集列表的逻辑
  const renderSelectedDatasetsList = () => {
    if (totalSelectedCount === 0) {
      return <div className="py-8 text-center text-sm text-gray-400">暂未选择知识库</div>;
    }

    return (
      <>
        {selectedDatasets.datasets.length > 0 && (
          <div className="mb-3">
            <div className="mb-2 text-xs font-medium text-text-5">知识库文件</div>
            {selectedDatasets.datasets.map((dataset) =>
              renderSelectedDatasetItem(dataset, 'datasets'),
            )}
          </div>
        )}

        {selectedDatasets.function.length > 0 && (
          <div>
            <div className="mb-2 text-xs font-medium text-text-5">数据接口</div>
            {selectedDatasets.function.map((dataset) =>
              renderSelectedDatasetItem(dataset, 'function'),
            )}
          </div>
        )}
      </>
    );
  };

  // 提取渲染标签页的逻辑
  const renderTabs = () => (
    <div className="my-2 flex gap-2">
      {tabs.map((tab) => (
        <div
          key={tab.value}
          className="flex-1 cursor-pointer text-center"
          onClick={() => setActiveTab(tab.value)}
        >
          <div
            className={`${
              activeTab === tab.value ? 'border-b-2 border-primary text-primary' : ''
            } mx-auto w-fit`}
          >
            {tab.label}
          </div>
        </div>
      ))}
    </div>
  );

  // 提取渲染树形组件的逻辑
  const renderTree = () => (
    <div className="relative h-full max-h-[300px] overflow-auto">
      <Tree
        checkable
        treeData={activeTab === 'datasets' ? treeData.datasets : treeData.function}
        onCheck={handleTreeCheck}
        checkedKeys={currentSelectedDatasets.map((item) => item.key)}
      />
      {loading && (
        <div className="absolute inset-0 flex items-center justify-center">
          <CircleLoading />
        </div>
      )}
    </div>
  );

  return (
    <div className="flex min-h-[420px] rounded-lg border-[1px] border-line-4">
      <div className="flex w-1/2 flex-col gap-2 p-3">
        <Search
          placeholder="搜索知识库"
          value={searchValue}
          onChange={(e) => setSearchValue(e.target.value)}
          allowClear
        />
        {renderTabs()}
        {renderTree()}
      </div>
      <div className="w-[1px] bg-line-4" />
      <div className="w-1/2 p-3">
        <div className="mb-3 text-sm font-medium text-gray-700">已选{totalSelectedCount}</div>
        <div className="max-h-[360px] space-y-2 overflow-auto pr-1">
          {renderSelectedDatasetsList()}
        </div>
      </div>
    </div>
  );
};

export default SelectDataset;
